package exercise2;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

public class Client extends Thread {
	int arraySize = 0;
	ObjectInputStream is = null;
	ObjectOutputStream os = null;
	Socket so = null;
	public Client(int as) {
		arraySize = as;
		
	}
	
	public void run(){
		System.out.println("Connecting...");
		connect();
		new ClientThread().start();
	}

	private void connect() {
		try {
			so = new Socket("localhost", 3103);
			os = new ObjectOutputStream(so.getOutputStream());

			System.out.println("Connection established.");
		} catch (UnknownHostException e) {
			System.err.println("Socket could not be opened!!!");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Socket could not be opened!!!");
			e.printStackTrace();
		}
	}
	private class ClientThread extends Thread implements IBubbleCallback {
		int[] unsortedList;
		
		
		public void run() {
			unsortedList = new int[arraySize];

			for (int i = 0; i < arraySize; i++)
				unsortedList[i] = new Random().nextInt();
																		/*********************
																		 * /* call server here *
																		 *********************/
			System.out.println("Pushing the list...");
			pushTheList(new ToBeBubbled(unsortedList));
																		/*********************
																	 * /* do your own stuff *
																	 *********************/																	
			ToBeBubbled tbb = wait4callback();
			unsortedList = tbb.getList();
			bubbleCallback(unsortedList);
		}

		private ToBeBubbled wait4callback(){
			try {
				is = new ObjectInputStream(so.getInputStream());
				Object obj = is.readObject();
				so.close();
				if (obj instanceof ToBeBubbled) {
					return ((ToBeBubbled) obj);
				} else {
					System.out.println("No bubble");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			return null;
		}
		public void pushTheList(ToBeBubbled list) {
			try {
				os.writeObject(list);
				System.out.println("Object written... now waiting...");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void bubbleCallback(int[] result) {
			String output = "";

			for (int i = 0; i < 10 && i < unsortedList.length; i++)
				output += unsortedList[i] + "\n";
			output += "...";

			GUI.showMessageDialog("Die Liste des Threads " + Thread.currentThread().getName() + " wurde sortiert:\n" + output);
			
		}
	}
}
